import { IStackProps, IStackStyles, mergeStyleSets } from "@fluentui/react";
import { fs, path } from '@tauri-apps/api';
import { FileEntry } from "@tauri-apps/api/fs";
import { RS } from "../i18n/config";
export function camelToKebab(str: string) {
  return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
}
export function isUpperCamelCase(str: string) {
  return /^[A-Z][a-zA-Z0-9]*$/.test(str);
}
export function isValidLocalPath(path: string) {
  const pathRegex = /^[A-Za-z]:\\(?:[^\\/:*?"<>|\r\n]+\\)*[^\\/:*?"<>|\r\n]*$/;
  return pathRegex.test(path);
}
export const stackTokens = { childrenGap: 50 };
export const stackStyles: Partial<IStackStyles> = { root: { width: "100%" } };


export const columnProps: Partial<IStackProps> = {
  tokens: { childrenGap: 15 },
  styles: { root: { width: "100%", margin: '0 24px' } },
};
//@ts-ignore;
const isDevVar = "__REACT_DEVTOOLS_GLOBAL_HOOK__" in window;
export const isDev = () => isDevVar;

export const getServer2Path = async (forguncyPath: string) => {
  const website = "Website";
  const server2 = "Forguncy.Server2";
  const serverStartPath = await path.join(forguncyPath, website, 'javaAdapterServerBin', "adapter-server-start.jar");
  const exist = await fs.exists(serverStartPath);
  return exist ? website : server2;
};

export async function tryGetJavaApiFile(forguncyPath: string, prefix: string) {
  const jarPath = await path.join(forguncyPath, await getServer2Path(forguncyPath), 'javaAdapterServerBin');
  const exist = await fs.exists(jarPath);
  if (exist) {
    const files = await getFileWithoutSources(jarPath);
    const versions = files.filter(v => v.name?.indexOf(prefix) === 0 && v.name.split('.').pop() === 'jar').map(api => {
      if (api) {
        const fileName = api.name || '';
        const lastDotIndex = fileName.lastIndexOf('.');
        const fileNameWithoutExt = fileName.substring(0, lastDotIndex);
        const jarVersion = (fileNameWithoutExt.substring(prefix.length + 1));
        if (jarVersion.split('.').length === 4) {
          return jarVersion;
        }
      }
    });
    return getNewestVersion(versions);
  }
  return ''
}

const compareVersion = (v1: string, v2: string): number => {
  if (v1 === v2) {
    return 0;
  }

  const v1Components = v1.split('.');
  const v2Components = v2.split('.');

  const len = Math.min(v1Components.length, v2Components.length);

  // loop while the components are equal
  for (let i = 0; i < len; i++) {
    // A bigger than B
    // eslint-disable-next-line radix
    if (parseInt(v1Components[i]) > parseInt(v2Components[i])) {
      return 1;
    }

    // B bigger than A
    // eslint-disable-next-line radix
    if (parseInt(v1Components[i]) < parseInt(v2Components[i])) {
      return -1;
    }
  }

  // If one's a prefix of the other, the longer one is greater.
  if (v1Components.length > v2Components.length) {
    return 1;
  }

  if (v1Components.length < v2Components.length) {
    return -1;
  }

  // Otherwise they are the same.
  return 0;
};
export function getNewestVersion(versions: (string | undefined)[]) {
  let version = versions[0] || "";
  versions.forEach(current => {
    if (current && compareVersion(version, current) === -1) {
      version = current;
    }
  });
  return version;
}

export async function getFileWithoutSources(jarPath: string) {
  return (await fs.readDir(jarPath)).filter(v => v.name && v.name.indexOf("-sources.jar") == -1 && v.name.indexOf(".jar") == v.name.length - 4);
}

export async function copyPackageTools(fullInstallPath: string, withAutoinstall: boolean = false) {
  const packageToolPath = await path.join(fullInstallPath, "packageTools");
  await ensureDirectoryExists(packageToolPath);
  const source = await path.join(await path.resourceDir(), "packageTools", "packageZip_jwd.jar");
  const target = await path.join(fullInstallPath, "packageTools", "packageZip_jwd.jar");
  await fs.copyFile(source, target);
  if (withAutoinstall) {
    const source = await path.join(await path.resourceDir(), "packageTools", "autoInstall_jwd.jar");
    const target = await path.join(fullInstallPath, "packageTools", "autoInstall_jwd.jar");
    await fs.copyFile(source, target);
  }
}


export const contentStyles = mergeStyleSets({
  container: {
    display: 'flex',
    flexFlow: 'column nowrap',
    alignItems: 'stretch',
    minHeight: 'initial',
  },
});
export async function ensureDirectoryExists(path: string) {
  if (!await fs.exists(path)) {
    await fs.createDir(path, { recursive: true });
  }
  const files = await fs.readDir(path);
  if (files.length > 0) {
    throw new Error(RS.Folder_Not_Empty);
  }
}

export async function isIgnoreFolder(file: FileEntry, root: string) {
  const target = await path.join(root, "target");
  const idea = await path.join(root, ".idea");
  return file.path.startsWith(target) || file.path.startsWith(idea);
}